package com.atguigu.lease.common.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * Created by 小可乐$ on 2024/8/12$ 19:03$
 * description: int类型转换枚举类型的对象制造工厂
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                T[] enumConstants = targetType.getEnumConstants();
                for (T enumConstant : enumConstants) {
                    if (enumConstant.getCode().equals(Integer.parseInt(code))) {
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("code"+code+"参数非法");
            }
        };
    }
}
